/*
 * @Author: rock
 * @Date: 2025-05-23 17:39:42
 * @LastEditors: rock 
 * @LastEditTime: 2025-05-25 16:02:01
 * @FilePath: /002ThreadPool/main/main.cpp
 * @Description: Ctrl+Num1-> For Document; Ctrl+Num2-> For Function
 *
 * Copyright (c) 2025 by rock, All Rights Reserved.
 */

#include "threadpool.h"
using uLong = unsigned long long;
// test class MyTask
class MyTask : public Task
{
public:
    MyTask()
    {}
    ~MyTask()
    {}

    MyTask(int begin, int end)
        :begin_(begin)
        ,end_(end)
    {

    }

    //run方法最终是在线程池分配的线程中做事情
    Any run()
    {
        LOG("\tbegin, run, tId:" << std::this_thread::get_id());

        //执行过程两秒
        //std::this_thread::sleep_for(std::chrono::seconds(5));

        uLong sum = 0;
        for(uLong i = begin_; i<=end_; i++)
        {
            sum+=i;
        }        

        LOG("\t  end, run, tId:" << std::this_thread::get_id());
        std::this_thread::sleep_for(std::chrono::seconds(5));
        return sum;
    }
private:
    int begin_;
    int end_;

};

void sleep_for_main(int i)
{
    // main线程睡5秒等待线程池中的线程执行完毕
    LOG("main thread sleep for 5s ...");
    std::this_thread::sleep_for(std::chrono::seconds(i));
}

int main()
{
    ThreadPool pool;
    pool.start(4);


    Result res1 = pool.submitTask(std::make_shared<MyTask>(1, 100000000));
    Result res2 = pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
    Result res3 = pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
    Result res4 = pool.submitTask(std::make_shared<MyTask>(1, 300000000));


    uLong sum1 = res1.get().cast_<uLong>();
    uLong sum2 = res2.get().cast_<uLong>();
    uLong sum3 = res3.get().cast_<uLong>();
    uLong sum4 = res4.get().cast_<uLong>();
    

    LOG("sum = " << sum1+sum2+sum3);
    LOG("sum = " << sum4);
    


    // pool.submitTask(std::make_shared<MyTask>());
    // pool.submitTask(std::make_shared<MyTask>());
    // pool.submitTask(std::make_shared<MyTask>());
   

    sleep_for_main(20);

    return 0;
}